package com.qf.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.qf.aop.IsLogin;
import com.qf.constant.Constant;
import com.qf.entity.Cart;
import com.qf.entity.User;
import com.qf.result.ResultMsg;
import com.qf.service.ICartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Author：刘亚康
 * @Date：2020/4/9
 * @QQ：50770284
 * @Phone：18235947935
 * @Desc : 购物车Controller
 **/
@Controller
@RequestMapping("cart")
@Slf4j
public class CartController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Reference
    private ICartService cartService;

    /**
     * 添加商品进购物车
     * @param cart
     * @param callback
     * @param user
     * @param cartToken
     * @param response
     * @return
     */
    @RequestMapping("addCart")
    @IsLogin(mustLogin = false)
    @ResponseBody
    public String addGoodsToCart(Cart cart, String callback, User user, @CookieValue(name = Constant.CART_TOKEN,required = false)String cartToken, HttpServletResponse response){
        //1：判断购物车token是否为空
        if (StringUtils.isEmpty(cartToken)) {
            log.info("用户未登陆，自动添加token");
            cartToken = UUID.randomUUID().toString();
            Cookie cookie = new Cookie(Constant.CART_TOKEN,cartToken);
            cookie.setMaxAge(60*60*24*7);
            cookie.setPath("/");
            cookie.setHttpOnly(false);
            response.addCookie(cookie);

        }
        log.info("购物车添加内容"+cart);
        int addResult=cartService.addGoodsToCart(cart,user,cartToken);

        return callback==null?addResult+"":callback+"('"+addResult+"')";
    }

    /**
     * 获取购物车所有内容
     * @param user
     * @param cartToken
     * @param map
     * @return
     */
    @RequestMapping("getCartList")
    @IsLogin(mustLogin = false)
    public String getCartList(User user, @CookieValue(name = Constant.CART_TOKEN,required = false)String cartToken, ModelMap map){
        log.info("获取购物车所有商品");
        List<Cart> cartList=cartService.getCartList(user,cartToken);
        //计算商品小计和
        BigDecimal bigDecimal=new BigDecimal(0);
        for (Cart cart : cartList) {
            bigDecimal=bigDecimal.add(cart.getGoodsSubtotal());
        }
        log.info("获取到购物车所有商品"+cartList.toString());
        map.put("cartList",cartList);
        map.put("goodsSubtotal",bigDecimal);
        return "cart";
    }

    /**
     * 获取购物车数量
     * @param callback
     * @param user
     * @param cartToken
     * @return
     */
    @RequestMapping("getUserCartCount")
    @IsLogin(mustLogin = false)
    @ResponseBody
    public String getUserCartCount(String callback,User user, @CookieValue(name = Constant.CART_TOKEN,required = false)String cartToken){

        Integer cartCount=cartService.getUserCartCount(user,cartToken);
        log.info("获取购物车商品数量"+cartCount);
        return callback==null?cartCount+"":callback+"('"+cartCount+"')";
    }

    /**
     * 修改购物车中商品的数量
     * @param callback
     * @param user
     * @param cartToken
     * @return
     */
    @RequestMapping("updateNum")
    @IsLogin(mustLogin = false)
    @ResponseBody
    public String updateNum(String callback,Cart cart,User user, @CookieValue(name = Constant.CART_TOKEN,required = false)String cartToken){
        log.info("修改购物车中的商品数量"+cart);
        Cart cartSum=new Cart();

        List<Cart> cartList=cartService.updateCartNum(cart,user,cartToken);

        BigDecimal bigDecimal=new BigDecimal(0);
        for (Cart cart1 : cartList) {
            if (cart1.getGoodsId().equals(cart.getGoodsId())) {
                cartSum=cart1;
            }
            bigDecimal=bigDecimal.add(cart1.getGoodsSubtotal());
        }
        Map<Object,Object> map=new HashMap<>();
        map.put("goodsSubtotal",cartSum.getGoodsSubtotal());
        map.put("subTotalSum",bigDecimal);
        //String result = cartSum.getGoodsSubtotal().toString();
        String result = JSON.toJSONString(map);
        return callback==null?result+"":callback+"('"+result+"')";
    }

    /**
     * 根据购物车id删除购物车
     * @param callback
     * @param cartId
     * @param user
     * @param cartToken
     * @return
     */
    @RequestMapping("del")
    @IsLogin(mustLogin = false)
    @ResponseBody
    public String del(String callback,Integer cartId,User user, @CookieValue(name = Constant.CART_TOKEN,required = false)String cartToken){
        log.info("删除购物车id:"+cartId);
        int deleteResult=cartService.deleteCart(user,cartToken,cartId);
        String resultMsg="";
        if (deleteResult>0) {
            resultMsg= JSON.toJSONString(ResultMsg.successMsg("删除成功"));
        }else {
            resultMsg= JSON.toJSONString(ResultMsg.fail("删除失败"));
        }
        return callback==null?resultMsg+"":callback+"('"+resultMsg+"')";
    }
}
